package com.stupidzhe.jdklearning.postfix;

import java.util.Stack;

/**
 * @Author: StupidZhe
 * @Date: Created in 2018/3/27
 * @Description:
 */
public class PostfixTest {
    public static String string2Postfix(String content) {
        StringBuilder res = new StringBuilder(20);
        char[] chars = content.toCharArray();
        Stack<Character> stack = new Stack<>();
        for (char c : chars) {
            if (Character.isDigit(c) || String.valueOf(c).trim().isEmpty()) {
                res.append(c);
                continue;
            }
            checkStack(res, stack, c);
        }
        while (stack.size() != 0)
            res.append(stack.pop());
        return res.toString();
    }

    private static void checkStack(StringBuilder res, Stack<Character> stack, char c) {
        if (stack.size() == 0) {
            stack.push(c);
            return;
        }
        if ('*' == c || '/' == c) {
            if ('+' == stack.peek() || '-' == stack.peek()) {
                stack.push(c);
            } else {
                res.append(stack.pop());
                checkStack(res, stack, c);
            }
        } else {
            res.append(stack.pop());
            checkStack(res, stack, c);
        }
    }

    public static void main(String[] args) {
        System.out.println(string2Postfix("1 + 1 * 2 - 3 * 4 + 1"));
    }
}
